<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>招聘系统聊天</h2>
      <p>与 {{ recipientName }} 聊天</p>
    </div>
    <div class="chat-messages" ref="chatMessages">
      <div v-for="(msg, index) in messages" :key="index" :class="msg.sender === 'me' ? 'message me' : 'message other'">
        <strong>{{ msg.sender === 'me' ? '我' : recipientName }}:</strong> {{ msg.content }}
      </div>
    </div>
    <div class="chat-input">
      <input v-model="message" placeholder="输入消息" @keyup.enter="sendMessage" />
      <button @click="sendMessage" :disabled="!connected">发送</button>
      <button @click="closeWebSocket" :disabled="!connected">关闭连接</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
const user = ref(getUser());
const connected = ref(false);
const ws = ref(null);
const message = ref('');
const messages = ref([]);
const recipientName = ref('招聘人员'); // 假设这是接收者的名称

const userId = ref(user.value.id) // 假设这是当前用户的ID
const recipientId = ref('4'); // 假设这是接收者的ID

const connectWebSocket = () => {
  ws.value = new WebSocket('ws://localhost:8080/chat');

  ws.value.onopen = () => {
    console.log('WebSocket连接成功');
    connected.value = true;
    ws.value.send(JSON.stringify({ type: 'login', userId: user.value.id }));
  };

  ws.value.onerror = (error) => {
    console.error('WebSocket出错:', error);
    alert('WebSocket出错: ' + error.message);
  };

  ws.value.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('收到消息:', data);
    messages.value.push({ sender: data.sender, content: data.content });
    scrollToBottom();
  };

  ws.value.onclose = () => {
    console.log('WebSocket连接已关闭');
    connected.value = false;
  };
};

const sendMessage = () => {
  if (ws.value && connected.value && message.value.trim()) {
    const msg = {
      type: 'message',
      sender: userId.value,
      recipientId: recipientId.value,
      content: message.value
    };
    ws.value.send(JSON.stringify(msg));
    messages.value.push({ sender: 'me', content: message.value });
    message.value = '';
    scrollToBottom();
  }
};

const closeWebSocket = () => {
  if (ws.value && connected.value) {
    ws.value.close();
  }
};

const scrollToBottom = async () => {
  await nextTick();
  const chatMessages = document.querySelector('.chat-messages');
  chatMessages.scrollTop = chatMessages.scrollHeight;
};

onMounted(() => {
  console.log('user的值：'+user.value.id);
  console.log('userId:'+userId.value)
  connectWebSocket();
});
</script>

<style scoped>
.chat-container {
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 16px;
  width: 400px;
  margin: 0 auto;
}

.chat-header {
  text-align: center;
  margin-bottom: 16px;
}

.chat-messages {
  height: 300px;
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 8px;
  margin-bottom: 16px;
}

.message {
  margin-bottom: 8px;
}

.message.me {
  text-align: right;
}

.message.other {
  text-align: left;
}

.chat-input {
  display: flex;
}

.chat-input input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 8px;
}

.chat-input button {
  padding: 8px 16px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.chat-input button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
